package com.dashu.authority.servie.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dashu.authority.common.Constant;
import com.dashu.authority.entity.AuthorityOperate;
import com.dashu.authority.entity.Menu;
import com.dashu.authority.entity.Role;
import com.dashu.authority.entity.User;
import com.dashu.authority.exception.AuthorityException;
import com.dashu.authority.repository.AuthorityOperateMapper;
import com.dashu.authority.repository.MenuMapper;
import com.dashu.authority.servie.AuthorityOperateService;
import com.dashu.authority.servie.RoleService;
import com.dashu.authority.servie.UserAndRoleService;
import com.dashu.authority.servie.UserService;
import com.dashu.authority.util.AuthorityServiceUtil;
import com.dashu.authority.util.Competence;

import net.sf.json.JSONObject;

@Service
public class AuthorityOperateServiceImpl extends BaseServiceImpl<AuthorityOperate> implements AuthorityOperateService{

	@Autowired
	private AuthorityOperateMapper operateMapper;
	@Autowired
	private UserAndRoleService userAndRoleService;
	@Autowired
	private UserService userService;
	@Autowired
	private	RoleService roleService;
	@Autowired
	private	MenuMapper menuMapper;
	private Competence comp = new Competence();
	@Override
	public List<AuthorityOperate> queryAllByExample(AuthorityOperate entity) throws AuthorityException {
		AuthorityServiceUtil.checkParam("查询条件", entity);
		Map<Object, Object> map = new HashMap<>();
		if (entity.getPersonnelSore()!=null&&!"".equals(entity.getPersonnelSore())) {
			map.put("personnelSore", entity.getPersonnelSore());
		}
		if (entity.getPersonnelId()!=null) {
			map.put("personnelId", entity.getPersonnelId());
		}
		if (entity.getOperateSore()!=null&&!"".equals(entity.getOperateSore())) {
			map.put("operateSore", entity.getOperateSore());
		}
		if (entity.getOperateId()!=null&&!"".equals(entity.getOperateId())) {
			map.put("operateId", entity.getOperateId());
		}
		if (map.size()==0) {
			AuthorityServiceUtil.checkParam("查询条件", "");
		}
		return	operateMapper.queryAllByExample(map);
	}

	@Override
	public Map<String, Object> insertEntity(AuthorityOperate entity) throws AuthorityException {
		AuthorityServiceUtil.checkParam("人员信息", entity);
		AuthorityServiceUtil.checkParam("人员类型", entity.getPersonnelSore());
		AuthorityServiceUtil.checkParam("人员id", entity.getPersonnelId());
		AuthorityServiceUtil.checkParam("资源类别", entity.getOperateSore());
		AuthorityServiceUtil.checkParam("资源id", entity.getOperateId());
		AuthorityServiceUtil.checkParam("权重值", entity.getAuthorityValue());
		int ret = operateMapper.insertEntity(entity);
		if(ret>0){
			return AuthorityServiceUtil.OperaSuccessMap(Constant.OPERATION_SAVE);
		}else{
			return AuthorityServiceUtil.OperaFailMap(Constant.OPERATION_SAVE);
		}
	}

	@Override
	public Map<String, Object> deleteByExample(AuthorityOperate entity) throws AuthorityException {
		AuthorityServiceUtil.checkParam("删除条件", entity);
		Map<Object, Object> map = new HashMap<>();
		if (entity.getPersonnelSore()!=null&&!"".equals(entity.getPersonnelSore())) {
			map.put("personnelSore", entity.getPersonnelSore());
		}
		if (entity.getPersonnelId()!=null) {
			map.put("personnelId", entity.getPersonnelId());
		}
		if (entity.getOperateSore()!=null&&!"".equals(entity.getOperateSore())) {
			map.put("operateSore", entity.getOperateSore());
		}
		if (entity.getOperateId()!=null&&!"".equals(entity.getOperateId())) {
			map.put("operateId", entity.getOperateId());
		}
		if (map.size()<2) {
			AuthorityServiceUtil.checkParam("删除条件", "");
		}
		int ret = operateMapper.deleteByByExample(map);
		if(ret>0){
			return AuthorityServiceUtil.OperaSuccessMap(Constant.OPERATION_SAVE);
		}else{
			return AuthorityServiceUtil.OperaFailMap(Constant.OPERATION_SAVE);
		}
	}


	/**
	 * 
	 * @ClassName: AuthorityOperateServiceImpl.java
	 * @Description: 根据用户id、资源类型 和系统id获取用户权限
	 * @author andy.wang
	 * @date 2017年9月26日 上午9:36:22 
	 * @param @return
	 * @return Map<Integer,Long>
	 * @throws AuthorityException 
	 *
	 */
	@Override
	public Map<Integer, Long> getAuthorityByUserAndType(Integer userId,String type,Integer applicationId,Integer operateId) throws AuthorityException{
		Map<Integer, Long> returnMap= new HashMap<Integer, Long>();
		Set<Integer> roles = userAndRoleService.querySuperiorRoleByUserId(userId);
		Map<Object, Object> params= new HashMap<Object, Object>();
		params.put("operateSore", type);//资源类型菜单
		if (applicationId!=null) {
			params.put("applicationId", applicationId);//资源类型菜单
		}
		if (operateId!=null) {
			params.put("operateId", operateId);//资源id
		}
		Competence com = new Competence();
		if (roles!=null&&roles.size()>0) {//角色权限处理
			params.put("personnelSore", Constant.PERSONNEL_TYPE_ROLE);//人员类型角色
			for (Integer roleId : roles) {//循环所有的角色包括所有的上级角色
				params.put("personnelId", roleId);
				List<AuthorityOperate> auths = operateMapper.queryAllByExample(params);
				if (auths!=null&&auths.size()>0) {
					for (int i = 0; i < auths.size(); i++) {
						Integer id= auths.get(i).getOperateId();
						Long l= returnMap.get(id);
						if (l==null) {
							returnMap.put(id,  auths.get(i).getAuthorityValue());//没有就添加
						}else{
							returnMap.put(id, com.ergerProduct(l, auths.get(i).getAuthorityValue()));//已经有了就合并
						}
					}
				}
			}
		}
		params.put("personnelSore", Constant.PERSONNEL_TYPE_USER);//人员类型用户
		params.put("personnelId", userId);
		List<AuthorityOperate> auths = operateMapper.queryAllByExample(params);
		if (auths!=null&&auths.size()>0) {
			for (int i = 0; i < auths.size(); i++) {
				Integer id= auths.get(i).getOperateId();
				Long l= returnMap.get(id);
				if (l==null) {
					returnMap.put(id,  auths.get(i).getAuthorityValue());//没有就添加
				}else{
					returnMap.put(id, com.ergerProduct(l, auths.get(i).getAuthorityValue()));//已经有了就合并
				}
			}
		}
		return returnMap;
	}

	//专门保存菜单资源权限
	@Override
	public Map<String, Object> insertMenuAuthority(String personnelType, Integer personnelId, Integer applicationId,
			String value) throws AuthorityException {
		AuthorityServiceUtil.checkParam("人员类型", personnelType);
		AuthorityServiceUtil.checkParam("人员id", personnelId);
		AuthorityServiceUtil.checkParam("系统id", applicationId);
		Integer id = null;
		if (Constant.PERSONNEL_TYPE_ROLE.equals(personnelType)) {
			Role role=	roleService.queryById(personnelId);
			if (role==null) {
				throw new AuthorityException("2100004");
			}else{
				id=role.getId();
			}
		} else if (Constant.PERSONNEL_TYPE_USER.equals(personnelType)) {
			User user =	userService.findUserById(personnelId);
			if (user==null) {
				throw new AuthorityException("2100005");
			}else{
				id=user.getId();
			}
		} else {
			throw new AuthorityException("2100003");
		}
		JSONObject auths = JSONObject.fromObject(value);
		Map<Object, Object> params = new HashMap<Object, Object>();
		params.put("applicationId", applicationId);
		List<Menu> list = menuMapper.queryAllByExample(params);
		if (list==null||list.size()==0) {
			throw new AuthorityException("2100006",new String[]{String.valueOf(applicationId)});
		}
		List<Integer> menuIds= new ArrayList<Integer>();
		for (Menu menu : list) {
			menuIds.add(menu.getId());
		}
		params = new HashMap<Object, Object>();
		params.put("personnelSore", personnelType);//人员类型
		params.put("personnelId", id);//人员id
		params.put("operateSore", Constant.RESOURCES_TYPE_MENU);//资源类型定死为菜单
		params.put("operateIds", menuIds);//这个系统下的所有菜单权限
		operateMapper.deleteByByExample(params);//删除这个人员之前所在这个系统的菜单权限
		List<AuthorityOperate> authList= new ArrayList<AuthorityOperate>();
		for (Integer menuId : menuIds) {
			Object o = auths.get(menuId.toString());
			if (o!=null) {
				AuthorityOperate auth = new AuthorityOperate();
				auth.setPersonnelSore(personnelType);
				auth.setPersonnelId(personnelId);
				auth.setOperateSore(Constant.RESOURCES_TYPE_MENU);
				auth.setOperateId(menuId);
				auth.setAuthorityValue(new Long(o.toString()));
				authList.add(auth);
			}
		}
		if (authList.size()==0) {
			return AuthorityServiceUtil.OperaSuccessMap(Constant.OPERATION_SAVE);
		}
		params = new HashMap<Object, Object>();
		params.put("list", authList);
		int ret = operateMapper.insertAll(params);
		if(ret>0){
			return AuthorityServiceUtil.OperaSuccessMap(Constant.OPERATION_SAVE);
		}else{
			return AuthorityServiceUtil.OperaFailMap(Constant.OPERATION_SAVE);
		}
	}
	
//	private Long getAuthorityValue(Object o){
//		String s =o.toString().trim();
//		String[] ss = s.split(",");
//		Integer[] i = new Integer[ss.length];
//		for (int j = 0; j < ss.length; j++) {
//			i[j]= Integer.valueOf(ss[j]);
//		}
//		return comp.getProduct(i);
//	}

	@Override
	public Map<Integer, Long> getAuthorityByUserAndResourcesType(String personnelType,
			Integer userId,String resourcesType,Integer applicationId) throws AuthorityException{
		AuthorityServiceUtil.checkParam("人员类型", personnelType);
		AuthorityServiceUtil.checkParam("人员id", userId);
		AuthorityServiceUtil.checkParam("资源类型", resourcesType);
		Map<Object, Object> params= new HashMap<Object, Object>();
		params.put("personnelSore", personnelType);//用户类型
		params.put("personnelId", userId);//用户id
		params.put("operateSore", resourcesType);//资源类型菜单
		params.put("applicationId", applicationId);
		List<AuthorityOperate> auths = operateMapper.queryAllByExample(params);
		Map<Integer, Long> returnMap = new HashMap<Integer, Long>();
		if (auths!=null&&auths.size()>0) {
			for (int i = 0; i < auths.size(); i++) {
				returnMap.put(auths.get(i).getOperateId(), auths.get(i).getAuthorityValue());//没有就添加
			}
		}
		return returnMap;
	}
	
}
